package site.luojie.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 真实Ip处理过滤器
 *
 * @author jie.luo
 * @since 2020/8/31
 */
@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER})
public class TransportIpFilter implements Filter {

    private final static Logger LOGGER = LoggerFactory.getLogger(TransportIpFilter.class);

    public final static String CONSUMER_REAL_REQUEST_IP = "customer-request-ip";

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        // 判断为消费者 还是 生产者
        if (RpcContext.getContext().isConsumerSide()) {
            // 消费者
            RpcContext.getContext().setAttachment(CONSUMER_REAL_REQUEST_IP, (String) RpcContext.getContext().get(CONSUMER_REAL_REQUEST_IP));
        } else {
            // 生产者
            String requestIp = RpcContext.getContext().getAttachment(CONSUMER_REAL_REQUEST_IP);
            LOGGER.info("请求IP ： " + requestIp);
        }

        return invoker.invoke(invocation);
    }

}
